#include "hal_api.h"
#include "printf.h"
#include <string.h>

#define EEPROM_DEVICE_ADDR        0x57
#define BUF_LEN                   8
#define EEPROM_ADDR               0x100
#define TEST_TIMES                8

static void compare_data(uint8_t *w_data, uint8_t *r_data, uint32_t len)
{
	uint32_t i;
	for (i = 0; i < len; i++)
	if (w_data[i] != r_data[i]) {
		printf("[I2C%d] write/read data err\r\n", I2C_ID_0);
		return;
	}
	printf("[I2C%d] write/read data OK\r\n", I2C_ID_0);
}

static int32_t eeprom_write_data(I2c_Id i2c, I2c_Addr_t addr, uint8_t *buf, uint32_t len)
{
	uint8_t write_buf[256];

	write_buf[0] = (uint8_t)((addr >> 8) & 0xFF);
	write_buf[1] = (uint8_t)(addr & 0xFF);
	memcpy(&write_buf[2], buf, len);

	return Hal_I2c_Write(i2c, write_buf, len + 2);

}

static int32_t eeprom_read_data(I2c_Id i2c, I2c_Addr_t addr, uint8_t *buf, uint32_t len)
{
	int ret;
	uint8_t write_buf[256];

	write_buf[0] = (uint8_t)((addr >> 8) & 0xFF);
	write_buf[1] = (uint8_t)(addr & 0xFF);

	ret = Hal_I2c_Write(i2c, write_buf, 2);
	if (ret) {
		return ret;
	}

	ret = Hal_I2c_Read(i2c, buf, len);
	return ret;
}

int32_t test_i2c(void)
{
	uint8_t read_buf[BUF_LEN] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
	uint8_t write_buf[BUF_LEN] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55};
	I2c_Addr_t addr = EEPROM_ADDR;
	uint8_t i;
	int32_t ret;

	printf("\r\n[I2C]: TEST START\r\n");
	ret = Hal_I2c_Tar_Add_Cfg(I2C_ID_0, EEPROM_DEVICE_ADDR);
	if (ret) {
		printf("[TSENSOR]: set i2c device addr err\r\n");
		return ret;
	}
	for (i = 0; i < TEST_TIMES; i++) {
		addr += BUF_LEN * i;
		ret = eeprom_write_data(I2C_ID_0, addr, write_buf, BUF_LEN);
		if (ret) {
			printf("[I2C%d] write data err\r\n", I2C_ID_0);
			return ret;
		}
		Hal_Cnt_DelayMs(500);
		ret = eeprom_read_data(I2C_ID_0, addr, read_buf, BUF_LEN);
		if (ret) {
			printf("[I2C%d] read data err\r\n", I2C_ID_0);
			return ret;
		}
		compare_data(write_buf, read_buf, BUF_LEN);
		Hal_Cnt_DelayMs(500);
	}
	printf("\r\n[I2C]: TEST END\r\n");

	return 0;
}

